<template>
  <el-dialog v-model="dialogInfo.visible" :title="dialogInfo.title" :width="dialogInfo.width" align-center>
    <el-form ref="formRef" label-position="left"  :model="formModel" :rules="formRules" label-width="120px">
      <el-row>
        <el-col :sm="24">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model.trim="formModel.taskName" autocomplete="off" placeholder="请输入任务名称" />
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="任务描述" prop="taskDescription">
            <el-input v-model.trim="formModel.taskDescription" autosize type="textarea" placeholder="请输入任务描述" />
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="任务教室" prop="tackRoom">
            <el-select class="w100" v-model="formModel.tackRoom" filterable multiple placeholder="请选择任务教室" autocomplete="off">
              <el-option v-for="item in bildingList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :sm="24">

          <el-form-item label="任务模式" prop="taskModel">
            <div class="d-flex flex-column text-white">
              <div>
                <el-radio-group v-model="formModel.taskModel">
                  <el-radio label="day">每天一次</el-radio>
                  <el-radio label="week">每周一次</el-radio>
                </el-radio-group>
              </div>
              <div v-show="formModel.taskModel=='day'">
                每天
                <el-time-select v-model="formModel.dayHour" :picker-options="{start: '00:00',step: '00:10',end: '23:50'}" placeholder="选择时间" style="width: 140px">
                </el-time-select>
                点执行

              </div>
              <div v-show="formModel.taskModel=='week'">
                每周
                <el-select v-model="formModel.day" style="width: 140px" placeholder="请选择任务状态" autocomplete="off">
                  <el-option label="周一" value="1"></el-option>
                  <el-option label="周二" value="2"></el-option>
                  <el-option label="周三" value="3"></el-option>
                  <el-option label="周四" value="4"></el-option>
                  <el-option label="周五" value="5"></el-option>
                  <el-option label="周六" value="6"></el-option>
                  <el-option label="周日" value="0"></el-option>
                </el-select>,
                <el-time-select v-model="formModel.dayHour" :picker-options="{start: '00:00',step: '00:30',end: '23:30'}" placeholder="选择时间" style="width: 140px">
                </el-time-select>
                点执行

              </div>
            </div>
          </el-form-item>

        </el-col>

        <el-col :sm="24">
          <el-form-item label="任务指令" prop="taskInstructions">
            <el-radio-group v-model="formModel.taskInstructions" size="mini">
              <el-radio label="1">一键上课</el-radio>
              <el-radio label="0">一键下课</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :sm="24">
          <el-form-item label="任务状态" prop="taskStatus">
            <el-radio-group v-model="formModel.taskStatus" size="mini">
              <el-radio label="1">启用</el-radio>
              <el-radio label="2">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="info"  plain @click="onCancel()">取消</el-button>
        <el-button type="primary"  @click="onSubmit()">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

  <script setup>
/**
* 编辑新增任务
*/
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { RegRule } from '@/utils/EsValidate';
import ImageUpload from '@/components/upload/ImageUpload.vue';

// ======================================================
//                      变量声明
// ======================================================

// emit
const emit = defineEmits(['success']);
// 表单数据
const formAttrs = {
  id: "",
  taskName: "",
  taskModel: "1",
  taskDescription: "",
  dayHour: "",
  day: "",
  hour: "",
  tackRoom: [],
  taskInstructions: "",
  taskStatus: "",
};
const formModel = ref(Object.assign({}, formAttrs));
// 弹窗信息
const dialogInfo = ref({
  visible: false,
  title: '',
  width: '600px',
})
// 表单组件的引用实例
const formRef = ref(null);
// 加载状态

// 选项数据
// 分类ID树形选项数据
const bildingList = ref([]);
// 是否热门选项数据
const optionsOfIsHot = ref({});
// 是否推荐选项数据
const optionsOfIsRecommend = ref({});
// 状态选项数据
const optionsOfStatus = ref({});
// 表单校验规则
const formRules = ref({
  taskName: [
    { required: true, trigger: "blur", message: "请输入任务名称" },
  ],
  tackRoom: [
    { required: true, trigger: "blur", message: "请选择任务教室" },
  ],
  taskInstructions: [
    { required: true, trigger: "blur", message: "请选择任务指令" },
  ],
  taskStatus: [
    { required: true, trigger: "blur", message: "请选择任务状态" },
  ],
})

// ======================================================
//                      点击操作
// ======================================================

// 点击提交按钮
const onSubmit = () => {
  console.log('[编辑表单] onSubmit formModel =', formModel.value);
  formRef.value.validate((valid, fields) => {
    if (!valid) {
      console.log('表单校验失败：', fields);
      return;
    }
    let url = formModel.value.id > 0 ? ApiUrls.articleUpdate : ApiUrls.articleSave;
    EsAjax.post(url, formModel.value).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      dialogInfo.value.visible = false;
      emit('success');
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  })
}

// 点击重置表单按钮
const onReset = () => {
  ElMessageBox.confirm('确定要重置表单数据吗？').then(() => {
    formRef.value.resetFields();
  }).catch(() => { })
}

// 点击取消按钮
const onCancel = () => {
  formModel.value = Object.assign({}, formAttrs);
  formRef.value.resetFields();
  dialogInfo.value.visible = false;
}

// ======================================================
//                      处理事件
// ======================================================


// 加载数据
const show = (id, title, item = null, width = '600px') => {
  dialogInfo.value.title = title;
  dialogInfo.value.width = width;
  dialogInfo.value.visible = true;

  // 加载选项数据
  EsAjax.post(ApiUrls.roomAll).then(res => {
    console.log('加载选项数据', res);
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    bildingList.value = res.data.data;
  }).catch(err => { ElMessage.error('网络错误：' + err.message) })

  // // 加载分类ID树形选项数据
  // EsAjax.post(ApiUrls.articleCategoryIndex, { params: { compact: 'y' } }).then(res => {
  //   console.log('加载分类ID树形选项数据', res);
  //   if (res.data.code !== 200) {
  //     ElMessage.warning(res.data.msg);
  //     return;
  //   }
  //   optionsOfCategoryId.value = res.data.data;
  // }).catch(err => { ElMessage.error('网络错误：' + err.message) })
  // // 加载详情数据
  if (id) {
    formModel.value = Object.assign({...formAttrs}, item);
  //   EsAjax.post(ApiUrls.articleRead, { params: { id: id } }).then(res => {
  //     console.log('加载详情数据', res);
  //     if (res.data.code !== 200) {
  //       ElMessage.warning(res.data.msg);
  //       return;
  //     }
  //     if (res.data.data) {
  //       ['is_hot', 'is_recommend', 'status'].forEach(name => {
  //         res.data.data[name] = res.data.data[name].toString();
  //       })
  //     }
  //     formModel.value = res.data.data ?? Object.assign({}, formAttrs);
  //   }).catch(err => { ElMessage.error('网络错误：' + err.message) })
  }
}

defineExpose({
  show
})
  </script>
